import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './user'
import { insertCartAPI, findNewCartListAPI, deleteCartAPI ,updateCartAPI} from '@/api/cart'

export const useCartStore = defineStore('cart', () => {
    // 登录状态
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)

    // 购物车列表
    const cartList = ref([])

    // 获取购物车列表
    const getCartList = async () => {
            const { data: res } = await findNewCartListAPI()
            cartList.value = res.result
    }

    // 计算购物车总价
    const total = computed(() => {
        let num = 0
        cartList.value.forEach(item => {
            num += (item.price * item.count)
        })
        return parseInt(num).toFixed(2)
    })

    // 计算选中状态时购物车商品总数量
    const checkSum = computed(() => {
        return cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0)
    })

    // 计算选中状态时购物车总价
    const checkTotal = computed(() => {
        return cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0)
    })

    // 计算购物车商品总数量
    const sum = computed(() => {
        let num = 0
        cartList.value.forEach(item => {
            num += item.count
        })
        return num
    })


    // 添加购物车
    const addCart = async (goods) => {
        if (isLogin.value) {
            const { skuId, count } = goods
            await insertCartAPI({ skuId, count })
            ElMessage.success('已添加购物车')
            await getCartList()
        } else {
            // 未登录
            // 已添加过 数量 + 1
            // 未添加过 push
            const item = cartList.value.find((item) => {
                return item.skuId === goods.skuId
            })
            if (item) {
                item.count++
            } else {
                cartList.value.push(goods)
            }
        }
    }

    // 删除购物车
    const delCart = async (skuId) => {
        if (isLogin.value) {
            await deleteCartAPI(Array(skuId))
            getCartList()
        } else {
            cartList.value = cartList.value.filter(item => item.skuId !== skuId)
        }
    }

    // 清楚购物车
    const clearCart = () =>{
        cartList.value = []
    }

    // 单选功能
    const singleCheck = (skuId, selected) => {
        const item = cartList.value.find((item) => {
            return item.skuId === skuId
        })
        item.selected = selected
    }
    // 全选功能
    const isAll = computed(() => {
        return cartList.value.every((item) => item.selected)
    })

    const checkAll = (selected) => {
        cartList.value.forEach(item => item.selected = selected)
    }

    return {
        cartList,
        total,
        sum,
        isAll,
        checkSum,
        checkTotal,
        getCartList,
        addCart,
        delCart,
        clearCart,
        singleCheck,
        checkAll
    }
}, {
    persist: true
})